package com.cskaoyan.service.admin;

import com.cskaoyan.bean.*;
import com.cskaoyan.bean.common.BasePageInfo;
import com.cskaoyan.bean.common.CommonData;
import com.cskaoyan.mapper.MarketKeywordMapper;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;

/**
 * @Description
 * @Author klw
 * @Data 2022/11/20 下午10:43
 */

@Service
public class KeywordServiceImpl implements KeywordService{

    @Autowired
    MarketKeywordMapper marketKeywordMapper;


    @Override
    public CommonData<MarketKeyword> query(String keyword, String url, BasePageInfo info) {
        PageHelper.startPage(info.getPage(), info.getLimit());
        MarketKeywordExample marketKeywordExample = new MarketKeywordExample();
        marketKeywordExample.setDistinct(true);
        MarketKeywordExample.Criteria criteria = marketKeywordExample.createCriteria();

        if(keyword != null && !"".equals(keyword)){
            criteria.andKeywordLike("%" + keyword + "%");
        }
        if(url != null && !"".equals(url)){
            criteria.andUrlEqualTo(url);
        }
        criteria.andDeletedEqualTo(false);

        marketKeywordExample.setOrderByClause(info.getSort() + " " + info.getOrder());
        List<MarketKeyword> marketKeywords = marketKeywordMapper.selectByExample(marketKeywordExample);
        PageInfo pageInfo = new PageInfo(marketKeywords);

        return CommonData.data(pageInfo);
    }

    @Override
    @Transactional
    public void delete(MarketKeyword marketKeyword) {
        Integer id = marketKeyword.getId();
        marketKeywordMapper.deleteById(id);
    }

    @Override
    public MarketKeyword createKeyword(MarketKeyword marketKeyword) {

        String keyword = marketKeyword.getKeyword();
        int res = marketKeywordMapper.selectByKeyword(keyword);
        if(res != 0){
            return null;
        }

        marketKeyword.setAddTime(new Date());
        marketKeyword.setUpdateTime(new Date());
        marketKeyword.setDeleted(false);
        marketKeyword.setSortOrder(1);

        if(marketKeyword.getIsHot() == null){
            marketKeyword.setIsHot(false);
        }
        if(marketKeyword.getIsDefault() == null){
            marketKeyword.setIsDefault(false);
        }

        marketKeywordMapper.insert(marketKeyword);
        return marketKeyword;
    }

    @Override
    public MarketKeyword updateKeyword(MarketKeyword marketKeyword) {
        marketKeyword.setUpdateTime(new Date());

        marketKeywordMapper.updateByPrimaryKeySelective(marketKeyword);

        return marketKeyword;
    }
}
